Using DISTINCT with Aggregate Functions like COUNT()
The DISTINCT keyword removes duplicate values before the aggregate function is applied. When used with functions like COUNT(), SUM(), AVG(), etc., it ensures the function operates only on unique values.
Counts unique (non-duplicate) values.
NULL values are ignored.
SUM(DISTINCT col) – Adds only unique values.
AVG(DISTINCT col) – Averages only unique values.
DISTINCT filters duplicates before applying the aggregate.
Useful when you want aggregation over unique values only.
COUNT(DISTINCT col1, col2) can count unique combinations of columns (MySQL-specific).
In summary: DISTINCT ensures that aggregate functions operate only on unique values, making results more precise when duplicates exist.